document.addEventListener('DOMContentLoaded', () => {
    const startBtn = document.getElementById('start-btn');
    const stopBtn = document.getElementById('stop-btn');
    const statusText = document.getElementById('status-text');
    const clientCount = document.getElementById('client-count');
    const startTime = document.getElementById('start-time');
    const endTime = document.getElementById('end-time');

    // 设置默认时间范围（当前时间前后12小时）
    const now = new Date();
    const twelveHoursAgo = new Date(now.getTime() - (12 * 60 * 60 * 1000));
    const twelveHoursLater = new Date(now.getTime() + (12 * 60 * 60 * 1000));
    
    startTime.value = twelveHoursAgo.toISOString().slice(0, 16);
    endTime.value = twelveHoursLater.toISOString().slice(0, 16);

    // 控制API
    async function startSimulation() {
        const start = new Date(startTime.value).getTime();
        const end = new Date(endTime.value).getTime();
        
        try {
            const response = await fetch('/api/simulation/start', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    start_time: start,
                    end_time: end
                })
            });
            
            if (response.ok) {
                startBtn.disabled = true;
                stopBtn.disabled = false;
                statusText.textContent = 'Running';
                statusText.style.color = '#28a745';
            }
        } catch (error) {
            console.error('Failed to start simulation:', error);
            alert('Failed to start simulation');
        }
    }

    async function stopSimulation() {
        try {
            const response = await fetch('/api/simulation/stop', {
                method: 'POST'
            });
            
            if (response.ok) {
                startBtn.disabled = false;
                stopBtn.disabled = true;
                statusText.textContent = 'Stopped';
                statusText.style.color = '#dc3545';
            }
        } catch (error) {
            console.error('Failed to stop simulation:', error);
            alert('Failed to stop simulation');
        }
    }

    // 更新连接数
    async function updateClientCount() {
        try {
            const response = await fetch('/api/simulation/status');
            const data = await response.json();
            clientCount.textContent = data.connected_clients;
        } catch (error) {
            console.error('Failed to update client count:', error);
        }
    }

    // 事件监听器
    startBtn.addEventListener('click', startSimulation);
    stopBtn.addEventListener('click', stopSimulation);

    // 定期更新状态
    setInterval(updateClientCount, 5000);
}); 